package com.studyweb.controller;

import com.studyweb.pojo.vo.Result;
import com.studyweb.pojo.entity.UserCheckin;
import com.studyweb.service.UserCheckinService;
import com.studyweb.service.UserAchievementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户签到控制器
 * 
 * @author StudyWeb Team
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/user/checkin")
public class UserCheckinController {

    @Autowired
    private UserCheckinService userCheckinService;
    
    @Autowired
    private UserAchievementService userAchievementService;

    /**
     * 用户签到
     * 
     * @param request HTTP请求
     * @return 签到结果
     */
    @PostMapping
    public Result checkin(HttpServletRequest request) {
        try {
            // 从请求属性中获取用户ID（由JWT拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            // 检查今日是否已签到
            if (userCheckinService.isCheckedInToday(userId)) {
                // 已签到，返回当前连续签到天数
                int consecutiveDays = userCheckinService.getConsecutiveDays(userId);
                Map<String, Object> data = new HashMap<>();
                data.put("consecutiveDays", consecutiveDays);
                data.put("alreadyCheckedIn", true);
                return Result.success("今日已签到", data);
            }
            
            // 执行签到
            UserCheckin checkin = userCheckinService.checkin(userId);
            
            // 获取用户最新积分
            int userPoints = userAchievementService.getUserPoints(userId);
            
            // 返回签到结果
            Map<String, Object> data = new HashMap<>();
            data.put("consecutiveDays", checkin.getStreakCount());
            data.put("checkinDate", checkin.getCheckinDate());
            data.put("pointsEarned", checkin.getPointsEarned());
            data.put("points", userPoints); // 添加用户最新积分
            data.put("alreadyCheckedIn", false);
            
            return Result.success("签到成功，获得" + checkin.getPointsEarned() + "积分", data);
        } catch (Exception e) {
            log.error("用户签到异常", e);
            return Result.error("签到失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户签到状态
     * 
     * @param request HTTP请求
     * @return 签到状态
     */
    @GetMapping("/status")
    public Result getCheckinStatus(HttpServletRequest request) {
        try {
            // 从请求属性中获取用户ID（由JWT拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            // 获取今日签到状态
            boolean checkedInToday = userCheckinService.isCheckedInToday(userId);
            
            // 获取连续签到天数
            int consecutiveDays = userCheckinService.getConsecutiveDays(userId);
            
            // 返回签到状态
            Map<String, Object> data = new HashMap<>();
            data.put("checkedInToday", checkedInToday);
            data.put("consecutiveDays", consecutiveDays);
            
            // 如果今日已签到，获取完整的签到记录信息
            if (checkedInToday) {
                UserCheckin todayCheckin = userCheckinService.getCheckinByDate(userId, LocalDate.now());
                if (todayCheckin != null) {
                    data.put("checkinId", todayCheckin.getCheckinId());
                    data.put("userId", todayCheckin.getUserId());
                    data.put("checkinDate", todayCheckin.getCheckinDate());
                    data.put("checkinTime", todayCheckin.getCheckinTime());
                    data.put("pointsEarned", todayCheckin.getPointsEarned());
                    data.put("createTime", todayCheckin.getCreateTime());
                    data.put("updateTime", todayCheckin.getUpdateTime());
                }
            }
            
            return Result.success("获取签到状态成功", data);
        } catch (Exception e) {
            log.error("获取签到状态异常", e);
            return Result.error("获取签到状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户月度签到记录
     * 
     * @param request HTTP请求
     * @param year 年份
     * @param month 月份
     * @return 月度签到记录
     */
    @GetMapping("/records/{year}/{month}")
    public Result getMonthlyCheckinRecords(HttpServletRequest request, 
                                          @PathVariable int year, 
                                          @PathVariable int month) {
        try {
            // 从请求属性中获取用户ID（由JWT拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            // 验证年份和月份参数
            if (year < 1900 || year > 2100 || month < 1 || month > 12) {
                return Result.error("无效的年份或月份参数");
            }
            
            // 获取指定月份的签到记录
            YearMonth yearMonth = YearMonth.of(year, month);
            LocalDate startDate = yearMonth.atDay(1);
            LocalDate endDate = yearMonth.atEndOfMonth();
            
            // 获取用户在指定月份的所有签到记录
            List<UserCheckin> checkinRecords = userCheckinService.getCheckinRecordsByDateRange(
                userId, startDate, endDate);
            
            // 构建日期状态映射
            Map<String, Boolean> dateStatus = new HashMap<>();
            for (UserCheckin record : checkinRecords) {
                dateStatus.put(record.getCheckinDate().toString(), true);
            }
            
            // 返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("year", year);
            data.put("month", month);
            data.put("dateStatus", dateStatus);
            data.put("checkinRecords", checkinRecords);
            data.put("checkinDays", checkinRecords.size());
            data.put("totalDays", yearMonth.lengthOfMonth());
            
            return Result.success("获取月度签到记录成功", data);
        } catch (Exception e) {
            log.error("获取月度签到记录异常", e);
            return Result.error("获取月度签到记录失败：" + e.getMessage());
        }
    }
}